<template>
  <view class="category-page">
    <view class="category-tab">
      <view
        v-for="category in categories"
        :key="category.id"
        :class="`category-tab-item ${
          selectedCategory == category.id ? 'selected' : ''
        }`"
        @tap="setSelectedCategory(category.id)"
      >
        {{ category.name }}
      </view>
    </view>
    <view class="products-list">
      <ProductList :list="categorieProducts" />
    </view>
  </view>
</template>

<script lang="ts">
import "./index.less";
import Taro from "@tarojs/taro";
import {
  getProducts,
  getProductCategories,
} from "../../../services/products-service";
import ProductList from "../components/productList/index.vue";

export default {
  data() {
    return {
      categorieProducts: [],
      categories: [],
      total: 0,
      selectedCategory: 0,
      totalPage: 0,
      currentPage: 0,
    };
  },
  components: { ProductList },
  methods: {
    async getTotalScore() {},
    async getTaskList() {},
    async getPersonalHealthyData() {},
    async getCategories() {
      this.categories = await getProductCategories();
      console.log("categoriespage", this.categories);
      this.$store.commit("setCategories", this.categories);
    },
    setSelectedCategory(category) {
      this.$store.commit("setSelectedCategory", category);
      this.selectedCategory = category;
      this.getProducts(category);
    },
    async getProducts(selectedCategory) {
      const current = Taro.getCurrentInstance();
      const category =
        selectedCategory || current.router?.params?.category || "0";
      this.$store.commit("setSelectedCategory", category);
      this.selectedCategory = category;
      console.log("this.selectedCategory", this.selectedCategory);
      const res = await getProducts({
        categories: parseInt(category),
        page: 1,
        size: 100,
        is_points_mall: false
      });
      this.$store.commit("setCategorieProducts", res.records);
      this.categorieProducts = res.records;
      this.total = res.total;
      this.totalPage = res.totalPage;
      console.log(res);
    },
  },

  async created() {},
  async mounted() {
    const { products } = this.$store.state;
    const { categories = [], categorieProducts } = products;
    this.getProducts();
    console.log("category-page-mounted", products);
    if (!categories.length) {
      this.getCategories();
    }
    this.categories = categories;
    this.categorieProducts = categorieProducts;
  },

  // onLoad
  onLoad() {},

  // onReady
  onReady() {},

  // 对应 onShow
  onShow() {},

  // 对应 onHide
  onHide() {},

  // 对应 onPullDownRefresh
  onPullDownRefresh() {},
};
</script>
